package projectmanagement.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.transaction.annotation.Transactional;

import projectmanagement.model.Project;
import projectmanagement.model.dao.ProjectDao;

@Transactional
public class ProjectDaoImpl implements ProjectDao{
	
	protected final Log logger = LogFactory.getLog(getClass());
	
	private EntityManager em;
	
	@PersistenceContext
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }
	 
	public List<Project> getProjectList() {
		logger.info("Getting person list!");
		
        List<Project> resultList = em.createQuery("select p from Project p").getResultList();
		return resultList;
	}	
	
	public Project getProjectById(int id) {
		logger.info("Getting project by id: " + id);
		
		return em.find(Project.class, id);
	}

	public void save(Project project) { 
		if (project.getId() == 0) {
            // new
            em.persist(project);
        } else {
            // update
            em.merge(project);
        }
	}
	
	public void remove(int id) {
		Project project  = getProjectById(id);
	        if (project != null) {
	            em.remove(project);
	        } 
	}

}
